const Koa = require('koa');
const app = new Koa();
const cors = require('koa2-cors');
const session = require('koa-session2');
// const session = require('koa-generic-session');
const views = require('koa-views');
const json = require('koa-json');
const onerror = require('koa-onerror');
const bodyparser = require('koa-bodyparser');
const logger = require('koa-logger');
const routeRegister = require('./routes/routeRegister');
const sessionRedisStore = require('./middlewares/session_redis_store');
// const redisStore = require('./dbs/redisCli');

// 设置跨域
app.use(cors({
  origin: (ctx) => ctx.header.origin,
  exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
  maxAge: 10,
  credentials: true,
  allowMethods: ['GET', 'PUT', 'POST', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
  allowHeaders: ['Content-Type', 'Authorization', 'Accept' ,'x-requested-with', 'origin'],
}));

onerror(app);

app.use(session({
    store: new sessionRedisStore()
}));
// app.use(session({
//   store: redisStore
// }));
// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}));
app.use(json());
app.use(logger());
app.use(require('koa-static')(__dirname + '/public'));

app.use(views(__dirname + '/views', {
  extension: 'pug'
}));

// logger
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

// routes
routeRegister(app);

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx);
});

module.exports = app;
